package com.guaika.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guaika.reggie.common.CustomException;
import com.guaika.reggie.common.ResultMessage;
import com.guaika.reggie.common.StringChars;
import com.guaika.reggie.entity.Category;
import com.guaika.reggie.entity.Dish;
import com.guaika.reggie.entity.Setmeal;
import com.guaika.reggie.mapper.CategoryMapper;
import com.guaika.reggie.service.CategoryService;
import com.guaika.reggie.service.DishServices;
import com.guaika.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

/**
 * @author GuaiKa
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    DishServices dishServices;

    @Autowired
    SetmealService setmealService;

    @Value("${reggie.path}")
    private String uploadPath;

    @Override
    public void remove(Long id) {
        //查询当前删除分类是否已关联菜品
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,id);
        int count = dishServices.count(dishLambdaQueryWrapper);
        if(count>0){
            throw new CustomException(StringChars.DELETE_CATEGORY_DISH_ERROR.getStr());
        }
        //查询当前删除分类是否已关联套餐
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        int count1 = setmealService.count(setmealLambdaQueryWrapper);
        if(count1>0){
            throw new CustomException(StringChars.DELETE_CATEGORY_SETMEAL_ERROR.getStr());
        }
        super.removeById(id);
    }


    @Override
    public ResultMessage<Page> categoryQuery(int page, int pageSize) {
        Page<Category> categoryPage = new Page(page, pageSize);
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(Category::getSort);
        this.page(categoryPage,lambdaQueryWrapper);

        return ResultMessage.success(categoryPage);
    }

    @Override
    public ResultMessage<List<Category>> listCategory(Category category) {
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper();
        //根据分类类型查询分类名
        lambdaQueryWrapper.eq(category.getType()!=null,Category::getType, category.getType());
        //排序
        lambdaQueryWrapper.orderByDesc(Category::getSort).orderByDesc(Category::getUpdateTime);
        //查询
        List<Category> list = this.list(lambdaQueryWrapper);
        return ResultMessage.success(list);
    }
}
